import re

from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer

import constants
from celery_tasks.email.task import send_verify_email
from goods.models import SKU
from users.models import User, Address
from areas.models import Area


class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""

    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.BooleanField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登陆状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')
        # 后端校验参数
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def create(self, validated_data):
        """创建用户"""
        user = User.objects.create_user(
            username=validated_data.get('username'),
            password=validated_data.get('password'),
            mobile=validated_data.get('mobile'),
        )

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """验证短信验证码"""
        if not value:
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, attr):
        # 判断两次密码是否相等
        password = attr['password']
        password2 = attr['password2']
        if not password == password2:
            raise serializers.ValidationError('两次密码输入不一致')

        # 验证短信验证码
        sms_code = attr['sms_code']
        mobile = attr['mobile']
        redis_conn = get_redis_connection('verify_codes')
        sms_code_default = redis_conn.get('sms_%s' % mobile)
        if not sms_code_default:
            raise serializers.ValidationError('验证码已过期')
        if sms_code != sms_code_default.decode():
            raise serializers.ValidationError('验证码输入错误')

        return attr


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


def generate_verify_email_url(self):
    """
    生成验证邮箱的url
    """
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)
    data = {'user_id': self.id, 'email': self.email}
    token = serializer.dumps(data).decode()
    verify_url = 'http://127.0.0.1:8080/success_verify_email.html?token=' + token
    return verify_url


class EmailSerializer(serializers.ModelSerializer):
    """验证邮箱序列化器"""
    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def validate_email(self, value):
        """验证邮箱"""
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',value):
            raise serializers.ValidationError('邮箱格式不正确')
        return value

    def update(self, instance, validated_data):
        """更新邮箱"""
        email = validated_data.get('email', instance.email)
        print(email)
        instance.email = email
        instance.save()
        # 生成验证url地址
        url = generate_verify_email_url(instance)
        print(url)
        send_verify_email.delay(email, url)
        return instance


class AreaSerializer(serializers.ModelSerializer):
    """
    行政区划信息序列化器
    """
    class Meta:
        model = Area
        fields = ('id', 'name')


class SubAreaSerializer(serializers.ModelSerializer):
    """
    子行政区划信息序列化器
    """
    subs = AreaSerializer(many=True, read_only=True)

    class Meta:
        model = Area
        fields = ('id', 'name', 'subs')


class UserAddressSerializer(serializers.ModelSerializer):
    """用户地址序列化器"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super(UserAddressSerializer, self).create(validated_data)


class UserPasswordSerializer(serializers.ModelSerializer):
    """修改密码序列化器"""

    password2 = serializers.CharField(label='新密码', write_only=True)
    password3 = serializers.CharField(label='确认新密码', write_only=True)

    class Meta:
        model = User
        fields = ('password', 'password2', 'password3')

    def update(self, instance, validated_data):
        user = self.context.get('request').user
        password = validated_data.get('password2')
        user.set_password(password)
        user.save()
        return user

    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')
        password3 = attrs.get('password3')

        # 验证旧密码
        user = self.context.get('request').user
        if not user.check_password(password):
            print(1)
            raise serializers.ValidationError('密码输入不正确')
        print(2)
        # 验证两次密码输入是否一致
        if password2 != password3:
            raise serializers.ValidationError('两次密码输入不一致')

        if password2 == password:
            raise serializers.ValidationError('新密码不能和旧密码一样')

        if not 8 < len(password2) < 20:
            raise serializers.ValidationError('密码为8-20位的随机字符')

        return attrs


class AddBrowseHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    'history_用户id': [sku_id列表]
    """
    sku_id = serializers.IntegerField()

    def validated_sku_id(self, value):
        # 校验sku_id是否存在
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        user = self.user
        user_id = user.id
        sku_id = validated_data.get('sku_id')
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 避免重复先删除一样的记录
        redis_conn.lrem('history_%s' % user_id, 0, sku_id)
        redis_conn.lpush('history_%s' % user_id, sku_id)
        # 只保存最多能5条记录
        redis_conn.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)

        pl.execute()

        return validated_data
